// src/services/captcha.service.js
import { Captcha } from "../models/captcha.js";
import { SMS } from "../utils/sms.js";

// 验证码有效期(5分钟)
const CAPTCHA_EXPIRE_TIME = 5 * 60 * 1000;
export class CaptchaService {
  static async generateAndSendCaptcha(phone, type) {
    // 生成6位随机数字
    const code = Math.floor(100000 + Math.random() * 900000).toString();

    // 保存到数据库
    await Captcha.create({
      phone,
      code,
      type,
      expiresAt: new Date(Date.now() + CAPTCHA_EXPIRE_TIME),
    });

    // 发送短信(实际项目中调用短信服务)
    await SMS.send(phone, `您的验证码是：${code}，5分钟内有效`);

    return code;
  }
  static async verifyCaptcha(phone, code, type) {
    // 查找最新验证码
    const captcha = await Captcha.findOne({
      where: { phone, type },
      order: [["createdAt", "DESC"]],
    });

    if (!captcha) {
      throw new Error("请先获取验证码");
    }

    if (captcha.code !== code) {
      throw new Error("验证码不正确");
    }

    if (new Date() > captcha.expiresAt) {
      throw new Error("验证码已过期");
    }

    // 验证成功后删除验证码
    await captcha.destroy();

    return true;
  }
}
